<?php
/**
 * User: coffee
 * Date: 2017/12/29
 * Time: 下午3:16
 */

namespace App\Http\Controllers;


use App\Exceptions\EventAppliedException;
use App\Exceptions\InvaildAppliedException;
use App\Exceptions\UserEventNotFoundException;
use App\Facades\Consumer;
use App\Http\Response\CreatedResponse;
use App\Http\Response\OKResponse;
use App\Models\EventStudentCalendarPresent;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class StudentEventsController extends Controller
{

    //2018送年历
    public function createStudentCalendarPresentEvent(Request $request)
    {
        $this->validate($request, [
            'name'      => 'required|string',
            'telephone' => 'required|integer|regex:/^(\+86)?1[34578][0-9]{9}$/',
            'address'   => 'required|string',
        ]);

        //chachong
//        EventAppliedException
        $studentEvent = EventStudentCalendarPresent::where('student_id', Consumer::getUserId())
            ->where('event_id', EventStudentCalendarPresent::EVENT_ID)->first();
        if (empty($studentEvent) || $studentEvent->getStatus() == EventStudentCalendarPresent::STATUS_Prohibit)
            throw new InvaildAppliedException();
        if ($studentEvent->getStatus() != EventStudentCalendarPresent::STATUS_Allow)
            throw new EventAppliedException();

        $studentEvent->setStudentId(Consumer::getUserId());
        $studentEvent->setName($request->input('name'));
        $studentEvent->setTelephone($request->input('telephone'));
        $studentEvent->setAddress($request->input('address'));
        $studentEvent->setStatus(EventStudentCalendarPresent::STATUS_Created);
        if ($request->has('province')) {
            $studentEvent->setProvince($request->input('province'));
            $studentEvent->setCity($request->input('city'));
        }
        $studentEvent->save();

        return new OKResponse();
    }

    public function retrieveStudentCalendarPresentEvent()
    {
        $studentEvent = EventStudentCalendarPresent::where('student_id', Consumer::getUserId())
            ->where('event_id', EventStudentCalendarPresent::EVENT_ID)->first();

        if (empty($studentEvent))
            throw new  UserEventNotFoundException();

        $data = [
            'title'     => $studentEvent->eventInfo->getTitle(),
            'name'      => $studentEvent->getName(),
            'telephone' => $studentEvent->getTelephone(),
            'address'   => $studentEvent->getAddress(),
            'status'    => $studentEvent->getStatus(),
        ];
        return JsonResponse::create($data);
    }
}
